package flash3.framework
{
	import flash.display.DisplayObjectContainer;

	public class LayerManager extends MapManager implements IUpdate
	{
		private var _layerList:Map = new Map();
		private var _curLayer:Layer = null;
		private var _container:DisplayObjectContainer = null;
		private var _curState:String;
		
		public function LayerManager()
		{
			UpdateManager.i.add(this);
		}
		
		static public function get i():LayerManager
		{
			return Singleton.getInstanceOrCreate(LayerManager) as LayerManager;
		}
		
		public function set container(parent:DisplayObjectContainer):void
		{
			_container = parent;
		}
		
		public function get container():DisplayObjectContainer
		{
			return _container;
		}

		public function changeState(id:String):void
		{
			if(!_container)
				throw new Error("_container为空！");
			
			if(!_map.containsKey(id))
				throw new Error(id + "状态不存在！");
			
			if(_curLayer)
			{
				_curLayer.leave();
				_container.removeChild(_curLayer);
			}
			
			if(!_layerList.containsKey(id))
			{
				var cls:Class = _map.getValue(id) as Class;
				_curLayer = new cls() as Layer;
			}
			else
			{
				_curLayer = _layerList.getValue(id);
			}
			
			_curState = id;
			
			_curLayer.enter();
			
			_container.addChild(_curLayer);
			
			_layerList.put(id, _curLayer);
		}
		
		public function update(lastTime:int):void
		{
			if(_curLayer)
				_curLayer.update(lastTime);
		}
		
		public function get curState():String
		{
			return _curState;
		}
	}
}